using Avalonia.BiliBili.Libs;
using Avalonia.BiliBili.Libs.Window;
using Avalonia.BiliBili.Units;
using Avalonia.BiliBili.ViewModels;
using Avalonia.BiliBili.Windows;
using Avalonia.Controls;
using Avalonia.Extensions.Controls;
using Avalonia.Extensions.Event;
using Avalonia.Input;
using Avalonia.Interactivity;
using Bilibili.Common;
using Bilibili.Common.Database;
using Bilibili.Common.Log;
using Bilibili.Model.Common;
using Bilibili.Model.Resource;
using Bilibili.Model.User;
using Bilibili.WebClient.Api;
using PCLUntils.Objects;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Avalonia.BiliBili.Views
{
    public partial class UserView : View
    {
        private Window loginWindow;
        public UserClient Client { get; }
        private int PageNum { get; } = 1;
        private UserViewModel ViewModel { get; }
        public UserView()
        {
            InitializeComponent();
            Client = new UserClient();
            ViewModel = new UserViewModel();
            InitializeComponent();
        }
        public override void AfterInitializeComponent()
        {
            DataContext = ViewModel;
            noAvatarImage.Tapped += NoAvatarImage_Tapped;
            StaticValue.LoginEvent = ReactiveCommand.Create(() =>  ViewModel.SetUserInfo());
        }
        private void NoAvatarImage_Tapped(object? sender, RoutedEventArgs e)
        {
            RunOnUiThread(ShowLoginWindow);
        }
        public void InitUserInfo(long userId) => InitUserInfo(userId.ToString());
        public void InitUserInfo(string userId)
        {
            try
            {
                userDynamic.Callback(new Tuple<string, string>(userId, "user"));
                RunOnUiThread(async () =>
                {
                    var isSelf = userId.Equals(SettingHelper.UserID.ToString());
                    ViewModel.IsSelf = isSelf;
                    if (userId.ToInt32(defaultValue: 0) != 0)
                    {
                        if (isSelf)
                        {
                            userId = SettingHelper.UserID.ToString();
                            ViewModel.SetUserInfo();
                        }
                        else
                        {
                            var result = await Client.GetUserInfo(userId.ToInt64(), isSelf);
                            if (result.IsSuccess())
                                ViewModel.SetUserInfo(result.Data);
                            else
                                PopupToast.Show(result.Message);
                        }
                    }
                    await GetUserContribute(userId);
                    followBangmi.ItemClick += FollowBangmi_ItemClick;
                    coinRecent.ItemClick += CoinRecent_ItemClick;
                });
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("InitUserInfo", ex);
            }
        }
        private void CoinRecent_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.ClickMouse == MouseButton.Left && e.ClickItem is GridViewItem item && item.Content is UserInfo userInfo)
                    App.Mapper.NavigateToPlayer(userInfo.Param, PlayMode.Video);
            }
            catch { }
        }
        private void FollowBangmi_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.ClickMouse == MouseButton.Left && e.ClickItem is GridViewItem item && item.Content is UserInfo model)
                    Navigater.OpenWindow<BanInfoWindow>(model.Param);
            }
            catch { }
        }
        private async Task GetUserContribute(string userId)
        {
            try
            {
                contributeList.ItemClick += ContributeList_ItemClick;
                var result = await Client.GetUserSubmit(userId, PageNum);
                if (result.IsSuccess())
                {
                    var model = result.Data;
                    if (model.IsNotEmpty())
                    {
                        if (model.Code == 0)
                        {
                            var list = model.Data["list"]["vlist"].ToObject<List<VideoList>>();
                            if (list != null && list.Count > 0)
                                contributeList.ItemsSource = list;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("GetUserContribute", ex);
            }
        }
        private void ContributeList_ItemClick(object? sender, ViewRoutedEventArgs e)
        {
            try
            {
                if (e.ClickMouse == MouseButton.Left && e.ClickItem is GridViewItem item && item.Content is VideoList userInfo)
                    App.Mapper.NavigateToPlayer(userInfo.Aid, PlayMode.Video);
            }
            catch { }
        }
        private async Task ShowLoginWindow()
        {
            try
            {
                if (SettingHelper.UserID == 0 && loginWindow == null)
                {
                    loginWindow = new LoginWindow();
                    var tabControl = (Parent as TabItem).Parent as TabControl;
                    var window = tabControl.Parent as Window;
                    await loginWindow.ShowDialog(window);
                    InitUserInfo(SettingHelper.UserID);
                    loginWindow = null;
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("ShowLoginWindow", ex);
            }
        }
        public void ClearView()
        {
            try
            {
                contributeList.ItemsSource = null;
                userDynamic.Callback("clear");
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError("ClearView", ex);
            }
        }
    }
}